<?php

namespace Simanx\Spes\Attribute\Event\Attributes;

use Attribute;
use Illuminate\Support\Arr;

/**
 * 事件监听器Attribute
 * @package Simanx\Spes\Event\Attributes
 */
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class Listen
{
    public array $events;

    /**
     * @param string|array $events
     * @param int|array $priority 优先级,值越大，执行越靠前，如果是数字，则表示所有监听的events优先级相同，否则分别指定对应优先级
     */
    public function __construct(string|array $events, public int|array $priority = 0)
    {
        $this->events = Arr::wrap($events);
    }

    public function getPriority(string $event)
    {
        if (is_int($this->priority)) {
            return $this->priority;
        }

        $eventIdx = array_search($event, $this->events);
        if (!$eventIdx) {
            throw new \InvalidArgumentException("has no event: $event listen in events: " . json_encode($this->events));
        }

        return $this->priority[$eventIdx];
    }
}